# -*- coding: utf-8 -*- #

import cgi
import os, uuid
import logging


from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from google.appengine.ext import db
from google.appengine.ext.webapp.util import run_wsgi_app

from google.appengine.api import users

from chatty import *


logging.getLogger().setLevel(logging.DEBUG)


#client
class ChatClient(webapp.RequestHandler):
	def get(self):
		uid = self.request.get('uid')
		session = self.request.get('session')
		sender = self.request.get('sender')

		template_values = {'uid':uid,'to':sender,'session':session}
		path = os.path.join(os.path.dirname(__file__), 'client.shtml')
		self.response.out.write(template.render(path, template_values))




class LoginPage(webapp.RequestHandler):
	def get(self):
		template_values = {}
		path = os.path.join(os.path.dirname(__file__), 'index.shtml')
		self.response.out.write(template.render(path, template_values))

class LoginAction(webapp.RequestHandler):
	def post(self):
		uid = self.request.get('uid')
		pwd = self.request.get('pwd')
		if uid != 'admin' and uid != 'andy':
			if pwd != 54321:
				self.response.out.write('authentication wrong!')
                                return

		result = UserSession.gql('WHERE uid=:1',uid).fetch(1)
		if result is not None and len(result) == 1:
			session = result[0]
			session.online=True
			session.put()

			skey = session.sessionkey
			memcache.set(skey,uid,3600)
		else:
			skey = str(uuid.uuid1())
			session = UserSession(uid=uid,sessionkey=skey,groupid=999,online=True)
			session.put()
			memcache.add(skey,uid,3600) #add session to memcache,used to update and expiration

		template_values = {'uin':uid,'session':skey}
		path = os.path.join(os.path.dirname(__file__), 'main.shtml')
		self.response.out.write(template.render(path, template_values))

class ChatMain(webapp.RequestHandler):
	def get(self):
		template_values = {}
		path = os.path.join(os.path.dirname(__file__), 'main.shtml')
		self.response.out.write(template.render(path, template_values))

application = webapp.WSGIApplication([
        ('/', LoginPage),
        ('/ls', Liss),
	('/client', ChatClient),
        ('/login', LoginAction),
        ('/main', ChatMain),
	('/newses', NewSession),
        ('/detect', MsgDetect),
        ('/chatty', Chatty),
	('/tasks/expire', SessionExpirer)
        ],debug=True)

def main():
        run_wsgi_app(application)

if __name__ == "__main__":
        main()
